﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Windows.Markup;


namespace MyWindowsMediaPlayer.Models
{
	class DatabaseMedia
	{
		public static List<MediaModel> parseXMLFile ( string type )
		{
			List<MediaModel> ret;
			string tmp = ".\\conf\\" + type;
			try
			{
				XDocument doc = XDocument.Load(tmp);
				ret = (from Media in doc.Root.Descendants("Item")
					select new MediaModel()
					{
						ItemPath = new Uri(Media.Attribute("ItemPath").Value),
						Name = Media.Attribute("Name").Value
					}).ToList<MediaModel>();
			}
			catch (Exception exc)
			{
				if (!Directory.Exists(".\\conf"))
					Directory.CreateDirectory(".\\conf");
				if (!File.Exists(tmp))
				{
					File.WriteAllText(tmp, @"<Items></Items>");
				}
				ret = parseXMLFile(type);

			}
			return ret;
		}

		public static List<MediaModel> FillXML ( string pathFolder, string pathXML, int type )
		{
			List<MediaModel> ret = null;
			string tmp = ".\\conf\\" + pathXML;
			if (pathFolder != null && pathFolder.Length > 0
				&& pathXML != null && pathXML.Length > 0)
			{
				DirectoryInfo dir = new DirectoryInfo(pathFolder);
				FileSystemInfo[ ] infos = dir.GetFileSystemInfos();
				XDocument doc = XDocument.Load(tmp);
				bool check;

				ret = new List<MediaModel>();

				foreach (FileSystemInfo info in infos)
					if (info is DirectoryInfo)
						FillXML(pathFolder + "\\" + info.Name, pathXML, type);
					else if (info is FileInfo)
					{
						if (type == 0 && Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".mp3"))
							check = true;
						else if (type == 1 && (Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".wmv") ||
								Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".avi") ||
								Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".mkv")))
							check = true;
						else if (type == 2 && (Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".png") ||
												Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".jpeg") ||
												Path.GetExtension(pathFolder + "\\" + info.Name).Equals(".gif")))
							check = true;
						else
							check = false;

						if (check == true)
						{
							MediaModel m = new MediaModel
							{
								Name = info.Name,
								ItemPath = new Uri(pathFolder + "\\" + info.Name)
							};
							if (ret.Contains(m) == false)
							{
								ret.Add(m);
								doc.Root.Add(new XElement("Item", new XAttribute("Name", m.Name),
								    new XAttribute("ItemPath", m.ItemPath)));
								doc.Save(tmp);
							}
							else
								m = null;
						}
					}
				
			}
			return ret;
		}

	}
}
